//
//  AppDelegate.m
//  Knockdoor
//
//  Created by acgera on 2018/4/9.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "AXAppDelegate.h"
#import "AXAppDelegate+Config.h"
#import "MHLoginViewModel.h"
#import "MHHomePageViewModel.h"
#import "MHSetCirclePriceViewModel.h"
#import <JPFPSStatus.h>
#import <Bugly/Bugly.h>
//#import <TXLiteAVSDK_UGC/TXUGCBase.h>
#import "TLSSDK/TLSRefreshTicketListener.h"
#import "MHCustomSearchBar.h"
#import "HSUpdateApp.h"
#import "MHDebugTouchView.h"
#import "MHPriceRange.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "CYLPlusButtonSubclass.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "MHCustomTip.h"
#import "MHInitalLocationModel.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "MHTabBarController.h"
//#import "TXUGCPublishTypeDef.h"
//#import "LXDAppFluecyMonitor.h"
#import "MHPublishRedPacketCallBack.h"
#import "MHSuccessCreateCircleView.h"
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#import <UserNotifications/UserNotifications.h>
#import "MHMHPushHelper.h"
#endif
#import "MHIMMessageTransferHelper.h"

#import "iVersion.h"

@interface AXAppDelegate ()<TXVideoPublishListener,TXVideoGenerateListener,TLSRefreshTicketListener,AMapLocationManagerDelegate,XGPushDelegate>{
#if DEBUG
    FBMemoryProfiler *memoryProfiler;
#endif
        IMALoginParam               *_loginParam;
}
@property (nonatomic, readwrite, strong) MHNavigationControllerStack *navigationControllerStack;
/// APP的服务层
@property (nonatomic, readwrite, strong) MHViewModelServicesImpl *services;

@property (nonatomic, strong) AMapLocationManager *locationManager;

@property (nonatomic, strong) AMapSearchAPI *search;

@property(nonatomic,readwrite, assign) BOOL isAuthorizationExpired;



//@property(nonatomic, strong) MHPublishRedPacketCallBack *callBack;

@end

@implementation AXAppDelegate


//- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
////    [super application:application didFinishLaunchingWithOptions:launchOptions];
//    self.window = [[UIWindow alloc]init];
//    self.window.frame = [UIScreen mainScreen].bounds;
//
//
//
//
//    return YES;
//}

+(void)initialize
{
    NSString *plistUrl = @"https://wx.miaodongquan.com/download/iosbailao.plist";
    NSDictionary *infoDic=[[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion=infoDic[@"CFBundleShortVersionString"];
    NSError *error = nil;
    NSURLResponse *response = nil;
    NSURL *url = [NSURL URLWithString:plistUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
#pragma clang diagnostic pop
    if (data)
    {
        NSPropertyListFormat format;
        NSDictionary *plistVersions = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListImmutable format:&format error:&error];
        
        NSArray *array =  plistVersions[@"items"];
        if (![array isKindOfClass:[NSArray class]] ) {
            return;
        }
        NSDictionary *metaData = array.firstObject;
        
        if (![metaData isKindOfClass:[NSDictionary class]] ) {
            return;
        }
        NSString *plistVersinString = metaData[@"metadata"][@"bundle-version"];
        __weak __typeof(self)weakSelf = self;
        if (![currentVersion isEqualToString:plistVersinString]) {
                UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"发现新版本" message:[NSString stringWithFormat:@"检测到新版本%@",plistVersinString] preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *updateAct = [UIAlertAction actionWithTitle:@"立即更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [weakSelf openAppStoreToUpdate];
                }];
                [alertC addAction:updateAct];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[AXAppDelegate sharedDelegate].window.rootViewController presentViewController:alertC animated:YES completion:^{
                    
                }];
            });
            
            
        }
    }
    
    
}


+ (void)openAppStoreToUpdate{
    NSURL *trackUrl = [NSURL URLWithString:@"itms-services://?action=download-manifest&url=https://wx.miaodongquan.com/download/iosbailao.plist"];
    if ([[UIApplication sharedApplication] canOpenURL:trackUrl]) {
        [[UIApplication sharedApplication] openURL:trackUrl];
    }
}

- (void)configAppLaunchWithOptions:(NSDictionary *)launchOptions
{
    self.window.backgroundColor = [UIColor whiteColor];
    [self _configThirdPart];
    self.isAuthorizationExpired = NO;
    self.imGroupImMessageUpdate = [[MHIMMessageTransferHelper sharedInstance] fetchChatIMMessageWithName:MHChacheIMGroupLastMessage]?:[NSMutableDictionary dictionary];
    [[XGPush defaultManager] reportXGNotificationInfo:launchOptions];
    self.services = [[MHViewModelServicesImpl alloc] init];
    self.navigationControllerStack = [[MHNavigationControllerStack alloc] initWithServices:self.services];
    [self _swithRootViewController];
    @weakify(self);
    [HSUpdateApp hs_updateWithAPPID:@"1406787352" withBundleId:@"com.miaodq.quanzi" block:^(NSString *currentVersion, NSString *storeVersion, NSString *openUrl, BOOL isUpdate) {
        @strongify(self);
        if (isUpdate) {
            [self showAlertViewTitle:@"新版本更新" subTitle:[NSString stringWithFormat:@"检测到新版本%@,是否更新？",storeVersion] openUrl:openUrl];
        }else{
            NSLog(@"当前版本%@,商店版本%@，不需要更新",currentVersion,storeVersion);
        }

    }];
   
    //判断是否已经推送过圈子
     YYCache *cache=[YYCache cacheWithName:MHCacheGlobleKey];
     NSNumber *number = [cache objectForKey:MHUploadedLocation];
    if (![number boolValue] || ![MHHTTPService sharedInstance].currentUser.isHasPushCircle) {
        [[[MHHTTPService sharedInstance] getUserCirclePushStatus] subscribeNext:^(MHHTTPResponse *respose) {
            BOOL alreadyPush =   ([[(NSDictionary *)respose  objectForKey:@"status"] intValue] == 1);
            @strongify(self);
            if (!alreadyPush) {
                [self startUpdatingLocation];
            }else
            {
                [cache setObject:@(true) forKey:MHUploadedLocation];
            }
        }];
    }
    
   
    [self.services resetRootViewModel:[self _chooseType]];
    [self.window makeKeyAndVisible];
    
    
    
    
  
    //分开请求
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self getH5LinkList];
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self getIllegalList];
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         [self.fetchIllegalList execute:nil];
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self getRedPacketConfig];
    });
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.fetchH5Command execute:nil];
    });
    
    [TXUGCBase setLicenceURL:@"http://license.vod2.myqcloud.com/license/v1/42003ce1c142554c34c267d6887d3437/TXUgcSDK.licence" key:@"9e00381d6a084de6980fae22a259b196"];
    NSLog(@"%@", [TXUGCBase getSDKVersionStr]);
    [[UIBarButtonItem appearanceWhenContainedIn:[MHCustomSearchBar class], nil]
     setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:MHMetionTextColor, NSForegroundColorAttributeName, nil]
     forState:UIControlStateNormal];

    
#if DEBUG
    NSArray *filters = @[FBFilterBlockWithObjectIvarRelation([UIView class], @"_subviewCache"),
                         FBFilterBlockWithObjectIvarRelation([UIPanGestureRecognizer class], @"_internalActiveTouches")];
    
    FBObjectGraphConfiguration *configuration =
    [[FBObjectGraphConfiguration alloc] initWithFilterBlocks:filters
                                         shouldInspectTimers:NO];
    
    memoryProfiler = [[FBMemoryProfiler alloc] initWithPlugins:@[[CacheCleanerPlugin new],
                                                                 [RetainCycleLoggerPlugin new]]
                              retainCycleDetectorConfiguration:configuration];
    [memoryProfiler enable];
    [self _configDebugModelTools];
#endif
    
    void (^doNext)(MHPriceRange *) = ^(MHPriceRange *range){
        YYCache *cache=[YYCache cacheWithName:MHCacheGlobleKey];
        [cache setObject:range forKey:MHCirclePriceRange];
    };
    [[[[[MHHTTPService sharedInstance] getJoinCirclePriceRange] mh_parsedResults] doNext:doNext] subscribeNext:^(id x) {
        
    }];
    
#if CorporateSignature
    self.isAuthorizationExpired =  YES;
#else
    [[[MHHTTPService sharedInstance] getAuthorizationStatus] subscribeNext:^(MHHTTPResponse *respose) {
        if (![respose isKindOfClass:[NSDictionary class]]) {
            return ;
        }
        BOOL isAuthorizationExpired =  ([[(NSDictionary *)respose objectForKey:@"status"] intValue] == 1);
        self.isAuthorizationExpired =  isAuthorizationExpired;
        if (self.isAuthorizationExpired) {
            return;
        }
        [self.services resetRootViewModel:[self _chooseType]];
        [self.window makeKeyAndVisible];
    }];
#endif
    
    
}



-(void) startUpdatingLocation
{
     [AMapServices sharedServices].apiKey = KeyForGaoDe;
    self.locationManager = [[AMapLocationManager alloc]init];
    self.locationManager.delegate = self;
    [self.locationManager startUpdatingLocation];
}

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode;
{
    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    // 赋值给全局变量
//    self.location = location;

    [self searchAroundWhitLaction:location.coordinate];
    [self.locationManager stopUpdatingLocation];
    [MHLocationManager uploadLocationToRemote:location];
//    [[[MHHTTPService sharedInstance] userLocationWithLocation:location] subscribeNext:^(id x) {
//        YYCache *cache=[YYCache cacheWithName:MHCacheGlobleKey];
//        [cache setObject:@(true) forKey:MHUploadedLocation];
//    }];
}

- (void)searchAroundWhitLaction:(CLLocationCoordinate2D )coordinate {
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    
    //构造AMapPOIAroundSearchRequest对象，设置周边请求参数
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    // types属性表示限定搜索POI的类别，默认为：餐饮服务|商务住宅|生活服务
    // POI的类型共分为20种大类别，分别为：
    // 汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|
    // 医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|
    // 交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
    request.types = @"汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施";
    request.sortrule = 0;
    request.requireExtension = YES;
    //发起周边搜索
    [self.search AMapPOIAroundSearch: request];
}


- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if (response.pois.count == 0)
    {
        return;
    }
    [response.pois enumerateObjectsUsingBlock:^(AMapPOI *obj, NSUInteger idx, BOOL *stop) {
        
        if (obj.address.length > 0) {
            MHInitalLocationModel *model =  [MHInitalLocationModel new];
            model.lon = obj.location.longitude;
            model.lat = obj.location.latitude;
            model.adcode = obj.adcode;
            model.district = obj.district;
            model.address = obj.address;
            model.citycode = obj.citycode;
            model.areaName =obj.name;
            model.province = obj.province;
            model.city = obj.city;
            model.district = obj.district;
            *stop = YES;
//            [[[MHHTTPService sharedInstance] userLocationWithLocation:model] subscribeNext:^(id x) {
//                YYCache *cache=[YYCache cacheWithName:MHCacheGlobleKey];
//                [cache setObject:@(true) forKey:MHUploadedLocation];
//            }];
        }
    }];
    
}


-(void)showAlertViewTitle:(NSString *)title subTitle:(NSString *)subTitle openUrl:(NSString *)openUrl{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:subTitle preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        if([[UIDevice currentDevice].systemVersion floatValue] >= 10.0){
            if ([[UIApplication sharedApplication] respondsToSelector:@selector(openURL:options:completionHandler:)]) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl] options:@{} completionHandler:^(BOOL success) {
                    
                }];
            } else {
                BOOL success = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl]];
                NSLog(@"Open  %d",success);
            }
            
        } else{
            bool can = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:openUrl]];
            if(can){
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl]];
            }
        }
    }];
    [alertVC addAction:cancel];
    [alertVC addAction:sure];
    [self.window.rootViewController presentViewController:alertVC animated:YES completion:nil];
}



-(void) onGenerateComplete:(TXGenerateResult *)result
{
    
    
    if (result.retCode == 0) {
        if (_actionType == 0) {
            ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
            [library writeVideoAtPathToSavedPhotosAlbum:[NSURL fileURLWithPath:self.outPutPath] completionBlock:^(NSURL *assetURL, NSError *error) {
                if (error != nil) {
                    [UIWindow showTips:@"视频保存失败！"];
                }else{
                    [UIWindow showTips:@"视频保存成功啦！"];
                }
//                [self performSelector:@selector(dismissViewController) withObject:nil afterDelay:1];
            }];
        }else
        {
            if ( self.videoPublish) {
                TXVideoInfo *videoInfo = [TXVideoInfoReader getVideoInfo:self.outPutPath];
                TXPublishParam *publishParam = [[TXPublishParam alloc] init];
                publishParam.signature  =  [MHHTTPService sharedInstance].currentUser.vedioSign;
                publishParam.coverPath = [self getCoverPath:videoInfo.coverImage];
                publishParam.videoPath  = self.outPutPath;
                __weak __typeof(self)weakSelf = self;
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    [weakSelf.videoPublish publishVideo:publishParam];
                });
                
            }
        }
       
    
    }else{
        [self showVideoUpLoadVideoView];
        [[AXAppDelegate sharedDelegate] clearPublishDatas];
    }
}


-(NSString *)getCoverPath:(UIImage *)coverImage
{
    UIImage *image = coverImage;
    if (image == nil) {
        return nil;
    }
    
    NSString *coverPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"TXUGC"];
    coverPath = [coverPath stringByAppendingPathComponent:[self getFileNameByTimeNow:@"TXUGC" fileType:@"jpg"]];
    if (coverPath) {
        // 保证目录存在
        [[NSFileManager defaultManager] createDirectoryAtPath:[coverPath stringByDeletingLastPathComponent]
                                  withIntermediateDirectories:YES
                                                   attributes:nil
                                                        error:nil];
        
        [UIImageJPEGRepresentation(image, 1.0) writeToFile:coverPath atomically:YES];
    }
    return coverPath;
}

-(NSString *)getFileNameByTimeNow:(NSString *)type fileType:(NSString *)fileType {
    NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMdd_HHmmss"];
    NSDate * NowDate = [NSDate dateWithTimeIntervalSince1970:now];
    ;
    NSString * timeStr = [formatter stringFromDate:NowDate];
    NSString *fileName = ((fileType == nil) ||
                          (fileType.length == 0)
                          ) ? [NSString stringWithFormat:@"%@_%@",type,timeStr] : [NSString stringWithFormat:@"%@_%@.%@",type,timeStr,fileType];
    return fileName;
}


-(void) onPublishProgress:(NSInteger)uploadBytes totalBytes: (NSInteger)totalBytes
{
    CGFloat progress = (float)uploadBytes / totalBytes;
    self.uploadProgress = progress;
    
}



-(void) showVideoUpLoadVideoView
{
    MHSuccessCreateCircleView *succesView = [MHSuccessCreateCircleView mh_viewFromXib];
    UIViewController *topViewController =  self.window.rootViewController;
    if([topViewController isKindOfClass:[UINavigationController class]])
    {
         topViewController = (MHViewController *)[(UINavigationController *)self.window.rootViewController topViewController];
    }else
    {
        topViewController = self.window.rootViewController;
    }
    topViewController.zh_popupController = [zhPopupController new];
    succesView.titleLabel.text = @"发布失败";
    succesView.descLabel.text = self.createModel ?  [NSString stringWithFormat:@"您在%@圈上传的红包主题发布失败，\n红包金额将退到您的“可提现”金额内",self.publushCircleInfo.title]: [NSString stringWithFormat:@"您在%@圈上传的主题发布失败",self.publushCircleInfo.title] ;

    succesView.width = MH_SCREEN_WIDTH * 0.8;
    succesView.layer.cornerRadius = 8.0;
    succesView.masksToBounds = YES;
    [succesView.settingButton setTitle:@"知道了" forState:0];
    [topViewController.zh_popupController presentContentView:succesView];
    [succesView.dissmissButton bk_whenTapped:^{
        [topViewController.zh_popupController dismiss];
    }];
    [succesView.settingButton bk_whenTapped:^{
        [topViewController.zh_popupController dismiss];
    }];
}




- (void)onPublishComplete:(TXPublishResult *)result
{
    if (result.retCode != 0) {
//        [UIWindow showTips:@"发布失败！"];
        [self showVideoUpLoadVideoView];
        [[AXAppDelegate sharedDelegate] clearPublishDatas];
        return;
    }
    self.inUploading = NO;
    __block TXPublishResult *publishResult = result;
    __weak __typeof(self)weakSelf = self;
    self.result = result;
    [RACObserve([AXAppDelegate sharedDelegate], finishPublish) subscribeNext:^(NSNumber *number) {
        if([number boolValue] && [AXAppDelegate sharedDelegate].videoContent.length > 0 && publishResult && self.result == publishResult)
        {

            NSString *resultString = @"";
            if (self.currentSong == nil) {
                 resultString = [@{@"videoURL":result.videoURL,@"coverURL":result.coverURL,@"videoId":result.videoId} yy_modelToJSONString];
            }else
            {
                 resultString = [@{@"videoURL":result.videoURL,@"coverURL":result.coverURL,@"videoId":result.videoId,@"songId":([AXAppDelegate sharedDelegate].currentSong != nil ? @([AXAppDelegate sharedDelegate].currentSong.autoId): 0)} yy_modelToJSONString];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([AXAppDelegate sharedDelegate].videoContent.length <= 0) {
                    return ;
                }
                [AXAppDelegate sharedDelegate].uploadProgress = 1;
                if (self.createModel) {
                    @weakify(self);
                    [[[[MHHTTPService sharedInstance] bindShortVideoWithRecentId:self.callBack.autoId vedioData:resultString] mh_parsedResults] subscribeNext:^(MHMoment *moment) {
                        @strongify(self);
                        [MHNotificationCenter postNotificationName:MHReloadMomentPageDataNotification object:nil];
                        publishResult = nil;
                        [self clearPublishDatas];
                        IMAMsg *msg = [IMAMsg msgWithCustom:EIMAMSG_Custom param:[moment yy_modelToJSONString]];
                        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_SendMsgNotification object:msg];
                    } error:^(NSError *error) {
                        [self showVideoUpLoadVideoView];
                        publishResult = nil;
                        [self clearPublishDatas];
                    }];

                    
                }else
                {
//
                    @weakify(self);
                    [[[[MHHTTPService sharedInstance] publishRecentStoryWithCircleId:[AXAppDelegate sharedDelegate].publushCircleInfo.autoId content:[AXAppDelegate sharedDelegate].videoContent data:nil labels:nil recentType:1 askedUid:nil vedioData:resultString locationData:self.locationDataString] mh_parsedResults] subscribeNext:^(MHMoment *moment) {
                        @strongify(self);
                        [MHNotificationCenter postNotificationName:MHReloadMomentPageDataNotification object:nil];
                        publishResult = nil;
                        [self clearPublishDatas];
                        IMAMsg *msg = [IMAMsg msgWithCustom:EIMAMSG_Custom param:[moment yy_modelToJSONString]];
                        [[NSNotificationCenter defaultCenter] postNotificationName:kIMAMSG_SendMsgNotification object:msg];
                    } error:^(NSError *error) {
                        publishResult = nil;
                         [self showVideoUpLoadVideoView];
                        [self clearPublishDatas];
                       
                    }];
                }
               
            });
           
        }
    }];
}

-(void) clearPublishDatas
{
    [AXAppDelegate sharedDelegate].videoContent = @"";
    [AXAppDelegate sharedDelegate].locationDataString = @"";
    [AXAppDelegate sharedDelegate].currentSong = nil;
    [[AXAppDelegate sharedDelegate].txVideoEditer cancelGenerate];
    [[AXAppDelegate sharedDelegate].txVideoEditer stopPlay];
    [AXAppDelegate sharedDelegate].txVideoEditer = nil;
    [AXAppDelegate sharedDelegate].callBack = nil;
    [AXAppDelegate sharedDelegate].inUploading = false;
    [AXAppDelegate sharedDelegate].createModel = nil;
    [AXAppDelegate sharedDelegate].finishPublish = false;
    [AXAppDelegate sharedDelegate].bindSuccess = NO;
    [AXAppDelegate sharedDelegate].uploadProgress = 0;
    self.callBack = nil;
    self.videoPublish = nil;
}

-(void)_configThirdPart
{
    [AXAppDelegate configureKeyboardManager];
    [AXAppDelegate configThirdPartShareLogin];
    
    BuglyConfig *config = [[BuglyConfig alloc] init];
    config.unexpectedTerminatingDetectionEnable = YES;
    config.debugMode = YES;
    config.blockMonitorTimeout = 1000;
     config.blockMonitorEnable = YES;
    [Bugly startWithAppId:@"2403af3817" config:config];
    [[XGPush defaultManager] startXGWithAppID:2200318450 appKey:@"I4IP1J331DQH"  delegate:self];
    [[XGPush defaultManager] setXgApplicationBadgeNumber:0];
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    NSLog(@"%s======》",__func__);
    
    NSString *zero =[[[userInfo objectForKey:@"aps"] objectForKey:@"alert"] objectForKey:@"body"];
//    if (application.applicationState == UIApplicationStateActive) {
//        [self showAlertViewWithTitle:@"新消息提示" Message:zero ConfirmTitle:@"确定" CancelTitle:nil];
//    }
//    [self receiveRemoteNotificationWithUserInfo:userInfo];
}
//**
//收到推送的回调 //iOS 9.x 及以前，需要在 UIApplicationDelegate 的回调方法(如下)中调用上报数据的接口
//@param application  UIApplication 实例
//@param userInfo 推送时指定的参数
//@param completionHandler 完成回调
//*/
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    [[XGPush defaultManager] reportXGNotificationInfo:userInfo];



    if (application.applicationState == UIApplicationStateActive) {  //程序当前正处于前台

    }else if(application.applicationState == UIApplicationStateInactive){//程序处于后台
        [self jumpToIndexWithNotificationUserInfo:userInfo];
    }

    completionHandler(UIBackgroundFetchResultNewData);
}

// iOS 10 新增回调 API
// App 用户点击通知栏
// App 用户选择通知中的行为
// App 用户在通知中心清除消息
// 无论本地推送还是远程推送都会走这个回调
#if __IPHONE_OS_VERSION_MAX_ALLOWED >=     __IPHONE_10_0
- (void)xgPushUserNotificationCenter:(UNUserNotificationCenter *)center
      didReceiveNotificationResponse:(UNNotificationResponse *)response
               withCompletionHandler:(void (^)(void))completionHandler
{
    [[XGPush defaultManager] reportXGNotificationResponse:response];
    [self jumpToIndexWithNotificationUserInfo:response.notification.request.content.userInfo];
    completionHandler();
}

-(void) jumpToIndexWithNotificationUserInfo:(NSDictionary *)userInfo
{
    UIViewController *tabbar =  self.window.rootViewController;
    int index = 1;
    if ([[userInfo objectForKey:@"ext"] isEqualToString:@"group"]) {
        index = 0;
    }
    NSString *pushText = userInfo[@"aps"][@"alert"];
    if ([tabbar isKindOfClass:[MHTabBarController class]]) {
        MHTabBarController *clyTabbar = (MHTabBarController * )tabbar;
        if (clyTabbar.tabBarController.selectedIndex == index) {
            UINavigationController *nav =    (UINavigationController *)clyTabbar.tabBarController.selectedViewController;
            MHViewController *viewController =  nav.viewControllers.lastObject;
            [viewController.viewModel.services popToRootViewModelAnimated:YES];
        }
        UINavigationController *viewController = (UINavigationController *)clyTabbar.tabBarController.viewControllers[index];
        [MHSharedAppDelegate.navigationControllerStack popNavigationController];
        [MHSharedAppDelegate.navigationControllerStack pushNavigationController:(UINavigationController *)viewController];
        clyTabbar.tabBarController.selectedIndex = index;
    }
}



// App 在前台弹通知需要调用这个接口
- (void)xgPushUserNotificationCenter:(UNUserNotificationCenter *)center
             willPresentNotification:(UNNotification *)notification
               withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
    [[XGPush defaultManager] reportXGNotificationInfo:notification.request.content.userInfo];
    completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}

#endif


-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"%s",__func__);
    NSLog(@"[XGDemo] register APNS fail.\n[XGDemo] reason : %@", error);
    //    [[NSNotificationCenter defaultCenter] postNotificationName:@"registerDeviceFailed" object:nil];
}

//注册token的问题
- (void)xgPushDidRegisteredDeviceToken:(NSString *)deviceToken error:(NSError *)error {
    MHUser *user = [MHHTTPService sharedInstance].currentUser;
    if (user) {
        [[XGPushTokenManager defaultTokenManager] bindWithIdentifier:[NSString stringWithFormat:@"%@",user.uniqueID] type:XGPushTokenBindTypeAccount];
    }
    
}

- (void)xgPushDidReceiveRemoteNotification:(id)notification withCompletionHandler:(void (^)(NSUInteger))completionHandler {
    UIApplicationState  state = [UIApplication sharedApplication].applicationState;
    BOOL isActive = (state == UIApplicationStateActive);
    if ([notification isKindOfClass:[NSDictionary class]]) {
        [[XGPush defaultManager] reportXGNotificationInfo:(NSDictionary *)notification];
        completionHandler(UIBackgroundFetchResultNewData);
    } else if ([notification isKindOfClass:[UNNotification class]]) {
        
        [[XGPush defaultManager] reportXGNotificationInfo:((UNNotification *)notification).request.content.userInfo];
        completionHandler(isActive ?UNNotificationPresentationOptionBadge:(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert));
        NSDictionary *dic = ((UNNotification *)notification).request.content.userInfo;
        NSString *pushText = dic[@"aps"][@"alert"];
        [MHNotificationCenter postNotificationName:MHPushTextNotification object:@"您有新消息了~"];
    }
}

- (void)xgPushDidSetBadge:(BOOL)isSuccess error:(NSError *)error {
    NSLog(@"%s, result %@, error %@", __FUNCTION__, error?@"NO":@"OK", error);
}



- (void)xgPushDidFinishStart:(BOOL)isSuccess error:(NSError *)error {
    NSLog(@"%s, result %@, error %@", __FUNCTION__, isSuccess?@"OK":@"NO", error);
}

- (void)xgPushDidFinishStop:(BOOL)isSuccess error:(NSError *)error {
    
}



#pragma mark - 调试(DEBUG)模式下的工具条
- (void)_configDebugModelTools
{
    /// 显示FPS
    [[JPFPSStatus sharedInstance] open];
    
    /// 打开调试按钮
    [MHDebugTouchView sharedInstance];
    /// CoderMikeHe Fixed: 切换了根控制器，切记需要将指示器 移到window的最前面
    [self.window bringSubviewToFront:[MHDebugTouchView sharedInstance]];
}


-(void) loginByToken{
    
    @weakify(self);
    void (^doNext)(MHUser *) = ^(MHUser *user){
        @strongify(self);
//        [[self.services client] loginUser:user];
       
        dispatch_async(dispatch_get_main_queue(), ^{
            /// 发通知
            if (user) {
                [[NSNotificationCenter defaultCenter] postNotificationName:MHSwitchRootViewControllerNotification object:nil userInfo:@{MHSwitchRootViewControllerUserInfoKey:@(MHSwitchRootViewControllerFromTypeLogin)}];
            }else
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:MHSwitchRootViewControllerNotification object:nil userInfo:@{MHSwitchRootViewControllerUserInfoKey:@(MHSwitchRootViewControllerFromTypeFirstIn)}];
            }
            
        });
    };
    [[[self.services.client loginByToken] mh_parsedResults] doNext:doNext];
}

-(void) _swithRootViewController{
    @weakify(self);
    /// 监听切换根控制器的通知
    [[MHNotificationCenter rac_addObserverForName:MHSwitchRootViewControllerNotification object:nil] subscribeNext:^(NSNotification * note) {
        /// 这里切换根控制器
        @strongify(self);
        // 重置rootViewController
        MHSwitchRootViewControllerFromType fromType = [note.userInfo[MHSwitchRootViewControllerUserInfoKey] integerValue];
        //        NSLog(@"fromType is  %zd" , fromType);
        /// 切换根控制器
        [self.services resetRootViewModel:[self _createInitialViewModel:fromType]];
        /// 切换了根控制器，切记需要将指示器 移到window的最前面
#if defined(DEBUG)||defined(_DEBUG)
                [self.window bringSubviewToFront:[MHDebugTouchView sharedInstance]];
                [[MHDebugTouchView sharedInstance] setHide:false];
#endif
    }];
    
    
}

+ (AXAppDelegate *)sharedDelegate{
    return (AXAppDelegate *)[[UIApplication sharedApplication] delegate];
}


-(MHViewModel * )_chooseType
{
    MHSwitchRootViewControllerFromType type;
    if (self.services.client.currentUser.userToken.length > 0 ) {
        type = MHSwitchRootViewControllerFromTypeLogin;
        [self autoLogin];
    }else
    {
        type = MHSwitchRootViewControllerFromTypeFirstIn;
    }
    return [self _createInitialViewModel:type];
}

- (void)autoLogin
{
    
    BOOL isAutoLogin = [IMAPlatform isAutoLogin];
    if (isAutoLogin)
    {
        _loginParam = [IMALoginParam loadFromLocal];
    }
    else
    {
        _loginParam = [[IMALoginParam alloc] init];
    }
    
    [IMAPlatform configWith:_loginParam.config];
    if ([_loginParam isExpired] && [_loginParam isVailed])
    {
        [[TLSHelper getInstance] TLSRefreshTicket:_loginParam.identifier andTLSRefreshTicketListener:self];
        [self loginIMSDK];
    }else
    {
        [self loginIMSDK];
    }
}

- (MHViewModel *)_createInitialViewModel:(MHSwitchRootViewControllerFromType ) type {
    if(type == MHSwitchRootViewControllerFromTypeLogin){
        return [[MHHomePageViewModel alloc] initWithServices:self.services params:nil];
    }else if(type == MHSwitchRootViewControllerFromTypeNewFeature) {
        return [[MHHomePageViewModel alloc] initWithServices:self.services params:nil];
    }else
    {
        return [[MHLoginViewModel alloc] initWithServices:self.services params:nil];
    }
}

- (void)loginIMSDK
{
    //直接登录
    __weak __typeof(self)weakSelf = self;
    [[IMAPlatform sharedInstance] login:_loginParam succ:^{
        [[IMAPlatform sharedInstance] configOnLoginSucc:_loginParam];
        
        [MHNotificationCenter postNotificationName:MHIMLoginSuccessNotification object:nil];
    } fail:^(int code, NSString *msg) {

    }];
}

- (void)registNotification
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    else
    {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
    }
}


- (void)OnRefreshTicketSuccess:(TLSUserInfo *)userInfo
{
    [[HUDHelper sharedInstance] syncStopLoading];
    [self loginWith:userInfo];
}

- (void)loginWith:(TLSUserInfo *)userinfo
{
    //    _openQQ = nil;
    //    _tlsuiwx = nil;
    dispatch_async(dispatch_get_main_queue(), ^{
        if (userinfo)
        {
            self->_loginParam.identifier = userinfo.identifier;
            self->_loginParam.userSig = [[TLSHelper getInstance] getTLSUserSig:userinfo.identifier];
            self->_loginParam.tokenTime = [[NSDate date] timeIntervalSince1970];
            [self loginIMSDK];
        }
    });
}


- (void)OnRefreshTicketFail:(TLSErrInfo *)errInfo
{
    _loginParam.tokenTime = 0;
//    NSString *err = [[NSString alloc] initWithFormat:@"刷新票据失败\ncode:%d, error:%@", errInfo.dwErrorCode, errInfo.sErrorTitle];

    [self _createInitialViewModel:MHSwitchRootViewControllerFromTypeFirstIn];
//    __weak __typeof(self)weakSelf = self;
//    [[HUDHelper sharedInstance] syncStopLoadingMessage:err delay:2 completion:^{
//
//    }];

}



- (void)OnRefreshTicketTimeout:(TLSErrInfo *)errInfo
{
    [self _createInitialViewModel:MHSwitchRootViewControllerFromTypeFirstIn];
}


@end
